from datetime import datetime

import peewee
import peewee_async # https://github.com/05bit/peewee-async

# db = peewee.SqliteDatabase("data.db")
db = peewee.MySQLDatabase("messages", host="127.0.0.1", port=3306, user="root", password="")

database = peewee_async.MySQLDatabase(database="messages", host="127.0.0.1", port=3306, user="root", password="")
database.set_allow_sync(False)

objects = peewee_async.Manager(database)


class BaseModel(peewee.Model):
    create_time = peewee.DateTimeField(default=datetime.now, verbose_name="创建时间")
    update_time = peewee.DateTimeField(default=datetime.now, verbose_name="修改时间")

    class Meta:
        database = db  # 指定连接的数据库
        # table_name = "goods"  # 指定表名


class Supplier(BaseModel):
    name = peewee.CharField(max_length=32, verbose_name="供应商名称", index=True)
    address = peewee.CharField(max_length=64, verbose_name="地址")
    phone = peewee.CharField(max_length=11, verbose_name="联系电话")

    class Meta:
        table_name = "supplier"


class Goods(BaseModel):
    name = peewee.CharField(max_length=100, verbose_name="商品名称", index=True)
    click_num = peewee.IntegerField(default=0, verbose_name="点击数")
    goods_num = peewee.IntegerField(default=0, verbose_name="库存数")
    price = peewee.DecimalField(max_digits=10, decimal_places=2, default=0.0, verbose_name="价格")
    brief = peewee.TextField(verbose_name="商品简介", null=True)
    supplier = peewee.ForeignKeyField(Supplier, verbose_name="商家", backref="goods")  # backref 通过这个参数很容易获取到商家下对应的商品

    class Meta:
        table_name = "goods"


def init_table():
    db.create_tables([Goods,Supplier])


if __name__ == '__main__':
    init_table()
